﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;

namespace HAZ.WinDBConnection.Forms
{
    public partial class Configurator : UserControl
    {
        ConnectionFactory.DBConnection dbconfig = ConnectionFactory.DBConnection.Default;
        String strLicenceFile;

        public Configurator()
        {
            InitializeComponent();
            dbconfig = new HAZ.ConnectionFactory.DBConnection();
        }

        private void Configurator_Load(object sender, EventArgs e)
        {
            #region [ OVERVIEW ]
            txtCodLoja.Text       = dbconfig.CodLoja; // Codigo da Loja.
            txtAlias.Text         = dbconfig.Alias; // Nome da Loja.
            txtImageRootPath.Text = dbconfig.ImagesRootPath; // Pasta das Imagens.
            txtStartMsg.Text      = dbconfig.StartMsg; // Mensagem inicial do sistema.
            #endregion

            #region [ DATABASE ]
            cbSGBDs.Items.Clear(); // SGBD
            foreach (string value in Enum.GetNames(typeof(DBSuported)))
                cbSGBDs.Items.Add(value);

            if (cbSGBDs.Items.Count > 0)
                cbSGBDs.SelectedIndex = dbconfig.SGBD;

            txtConnectionString.Text = dbconfig.connectionString; // Conexao com o Banco
            #endregion

            #region [ LICENÇA E SEGURANÇA ]
            txtPwdAccess.Text = dbconfig.PwdAcess;
            txtPwdConfig.Text = dbconfig.PwdConfig;
            txtSerial.Text    = Session.Serial;
            txtLicence.Text   = (txtSerial.Text == dbconfig.Licence ? "Licenciado" : "");
            #endregion

            #region [ OPÇÕES INTERNAS ]
            txtPwdInternal.Text = dbconfig.PwdInternal;
            #endregion

            if (Session.Password != dbconfig.PwdInternal)
                TabsCfg.TabPages.Remove(tabInternal);
        }

        private void btnFechar_Click(object sender, EventArgs e)
        {
            ToolsUtils.RemoveTab((TabControl)this.Parent.Parent, (TabPage)this.Parent);
        }

        private void btnSalvar_Click(object sender, EventArgs e)
        {
            #region [ OVERVIEW ]
            dbconfig.CodLoja        = txtCodLoja.Text.Trim();
            dbconfig.Alias          = txtAlias.Text.Trim();
            dbconfig.ImagesRootPath = txtImageRootPath.Text.Trim();
            dbconfig.StartMsg       = txtStartMsg.Text.Trim();
            #endregion

            #region [ DATABASE ]
            dbconfig.SGBD = cbSGBDs.SelectedIndex;
            dbconfig.connectionString = txtConnectionString.Text.Trim();
            #endregion

            #region [ LICENÇA E SEGURANÇA ]
            dbconfig.PwdAcess  = txtPwdAccess.Text.Trim();
            dbconfig.PwdConfig = txtPwdConfig.Text.Trim();
            if (!String.IsNullOrEmpty(strLicenceFile))
                dbconfig.Licence = strLicenceFile;
            #endregion

            #region [ OPÇÕES INTERNAS ]
            dbconfig.PwdInternal = txtPwdInternal.Text.Trim();
            #endregion

            dbconfig.Save();
        }

        private void btnImportLicence_Click(object sender, EventArgs e)
        {
            try
            {

                OpenFileDialog fDialog = new OpenFileDialog();
                fDialog.Filter = "Arquivos de Licença (*.licence)|*.licence|Todos os arquivos (*.*)|*.*";

                DialogResult result = fDialog.ShowDialog(); // Show the dialog and get result.
                if (result == DialogResult.OK) // Test result.
                {
                    /*
                    Stream str = new FileStream(fDialog.FileName, FileMode.Open);
                    IFormatter formatter = new BinaryFormatter();//new SoapFormatter();

                    //formatter.(str, license);
                    License license = formatter.Deserialize(str) as License;
                    str.Close();
                    //*/
                    /*
                    FileStream streamIn = new FileStream(fDialog.FileName, FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();
                    License license = bf.Deserialize(streamIn) as License;
                    streamIn.Close();
                    //*/


                    //*
                    Stream s = File.Open(fDialog.FileName, FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();

                    bf = new BinaryFormatter();
                    object o = bf.Deserialize(s);
                    License license = o as License;
                    
                    s.Close();
                    //*/

                    if (license == null)
                    {
                        MessageBox.Show("Arquivo de licença inválido ou corrompido");
                        return;
                    }

                    lblInfo.Text = license.ToString();

                    string licensefile = license.LicenseKey;
                    license.GenerateLicence();

                    if (license.LicenseKey != licensefile)
                    {
                        MessageBox.Show("Arquivo de licença Inválido ou corrompido");
                        return;
                    }

                    if (license.DataCompra > Session.DataAtual)
                    {
                        MessageBox.Show(String.Format("A data atual({0}) é inferior a data da compra da licença({1})."
                            , Session.DataAtual
                            , license.DataCompra));
                        return;
                    }
                    if (license.DataVencto < Session.DataAtual)
                    {
                        MessageBox.Show(String.Format("Arquivo de licença vencido({0}).\r\nConfira a licença usada!"
                            , license.DataVencto));
                        return;
                    }
                    if (license.SerialKey != Session.Serial)
                    {
                        MessageBox.Show("O arquivo de licença usado não é valido para o uso na maquina atual.\r\nConfira a licença usada!");
                        return;
                    }

                    strLicenceFile = license.SerialKey;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BtnGetDirectory_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.SelectedPath = txtImageRootPath.Text;

            //OpenFileDialog fDialog = new OpenFileDialog();
            //fDialog.Filter = "Arquivos de Imagem (*.jpg)|*.licence|Todos os arquivos (*.*)|*.*";

            //DialogResult result = fDialog.ShowDialog(); // Show the dialog and get result.
            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                txtImageRootPath.Text = folder.SelectedPath;
            }
        }
    }
}
